package my.diplom.web.validators;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.apache.log4j.Logger;
import my.diplom.entity.User;

/**
 * Created by IntelliJ IDEA.
 * User: GGobozov
 * Date: 21.08.2009
 * Time: 14:26:19
 * To change this template use File | Settings | File Templates.
 */
public class CreateUserValidator  implements Validator {

     private static final Logger log = Logger.getLogger(CreateUserValidator.class);

     public boolean supports(Class clazz) {
        return User.class.equals(clazz);
    }

     public void validate(Object target, Errors errors) {
         
        User user = (User) target;
         log.debug("validate user" + user.getLastName() + " " + user.getFirstName());
        if (user == null) errors.reject("Null data received");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.empty", "First name is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.empty", "Last name is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "login.empty", "Login is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.empty", "Email is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.empty", "Password is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.empty", "Role is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "status", "status.empty", "status is required");
         
        String password = user.getPassword();
        if (password == null || password.length() < 5 * 2) errors.rejectValue("password", "wrong.passwords", "Wrong password length!");

        String p1 = password.substring(0, password.length() / 2);
        String p2 = password.substring(password.length() / 2 + 1, password.length());
        if (! p1.equals(p2)) errors.rejectValue("password", "mismatch.passwords", "Mismatch passwords!");

        user.setPassword(p1);


    }


}
